<?php 
include_once("include/dbcommon.php");

	
if(!isset($pdf))
{
	$table = postvalue("table");
	$strTableName = GetTableByShort($table);
	
	if (!checkTableName($table))
	{
		exit(0);
	}
	
	include("include/".$table."_variables.php");
	@ini_set("display_errors","1");
	@ini_set("display_startup_errors","1");

	if(!@$_SESSION["UserID"] || !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Search"))
	{ 
		header("Location: login.php"); 
		return;
	}

	$field = postvalue("field");
	if(!CheckFieldPermissions($field))
		return DisplayNoImage();

	//	construct sql
	$keysArr = GetTableData($strTableName, '.Keys', array());
	$keys = array();
	foreach ($keysArr as $ind=>$k)
	{	
		$keys[$k]=postvalue("key".($ind+1));
	}	
}
else
{
	$table = @$params["table"];

	$strTableName = GetTableByShort($table);
	
	if (!checkTableName($table))
	{
		exit(0);
	}
	include("include/".$table."_variables.php");
	$field = @$params["field"];
	//	construct sql
	$keysArr = GetTableData($strTableName, '.Keys', array());
	$keys = array();
	foreach ($keysArr as $ind=>$k)
	{	
		$keys[$k]=@$params["key".($ind+1)];
	}
}

if(!$gQuery->HasGroupBy())
{
	// Do not select any fields except current (image) field.
	// If query has 'group by' clause then other fields are used in it and we may not simply cut 'em off.
	// Just don't do anything in that case.
	$gQuery->RemoveAllFieldsExcept(GetFieldIndex($field));
}

$where=KeyWhere($keys);

$secOpt = GetTableData($strTableName, '.nSecOptions', ADVSECURITY_NONE);
if ($secOpt == ADVSECURITY_VIEW_OWN)
{
	$where=whereAdd($where,SecuritySQL("Search"));	
}

$sql = gSQLWhere($where);

$rs = db_query($sql,$conn);

if(isset($pdf))
{
	if($rs && ($data=db_fetch_array($rs)))
		$file = $data[$field];
}
else
{

if(!$rs || !($data=db_fetch_array($rs)))
  return DisplayNoImage();


$value=db_stripslashesbinary($data[$field]);
if(!$value)
{
	if(postvalue("alt"))
	{
		$value=db_stripslashesbinary($data[postvalue("alt")]);
		if(!$value)
			return DisplayNoImage();
	}
	else
		return DisplayNoImage();
}

$itype=SupposeImageType($value);

if(!$itype)
{
	return DisplayFile();
}
if(!isset($pdf))
{
	header("Content-Type: ".$itype);
	header("Cache-Control: private");
	SendContentLength(strlen_bin($value));
}
echoBinary($value);
return;
}


?>
